package com.nbcio.cd.utils;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.security.SecureRandom;
import java.util.Random;

/**
 * 云网盘路径工具类
 *
 * @author nbacheng
 */
@Slf4j
public class CdPathUtils {

    private static final String SEPARATOR = "/";
    private static final String ROOT_PATH = "/";
    private static final Random RANDOM = new SecureRandom();

    /**
     * 生成分享码
     *
     * @return 分享码
     */
    public static String generateShareCode() {
        // 生成8位随机字符串，包含数字和字母
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder shareCode = new StringBuilder();
        
        for (int i = 0; i < 8; i++) {
            shareCode.append(chars.charAt(RANDOM.nextInt(chars.length())));
        }
        
        return shareCode.toString();
    }

    /**
     * 生成唯一ID
     *
     * @return 唯一ID
     */
    public static String generateUniqueId() {
        return IdUtil.simpleUUID();
    }

    /**
     * 构建文件路径
     *
     * @param parts 路径部分
     * @return 完整路径
     */
    public static String buildPath(String... parts) {
        if (parts == null || parts.length == 0) {
            return ROOT_PATH;
        }
        
        StringBuilder path = new StringBuilder();
        for (String part : parts) {
            if (StrUtil.isNotBlank(part)) {
                if (path.length() > 0 && !path.toString().endsWith(SEPARATOR)) {
                    path.append(SEPARATOR);
                }
                path.append(part);
            }
        }
        
        return path.toString();
    }

    /**
     * 规范化路径
     *
     * @param path 原始路径
     * @return 规范化后的路径
     */
    public static String normalizePath(String path) {
        if (StrUtil.isBlank(path)) {
            return ROOT_PATH;
        }
        
        // 确保路径以 / 开头
        if (!path.startsWith(SEPARATOR)) {
            path = SEPARATOR + path;
        }
        
        // 移除重复的 /
        path = path.replaceAll("/+", SEPARATOR);
        
        // 移除末尾的 /
        if (path.length() > 1 && path.endsWith(SEPARATOR)) {
            path = path.substring(0, path.length() - 1);
        }
        
        return path;
    }

    /**
     * 获取父路径
     *
     * @param path 当前路径
     * @return 父路径
     */
    public static String getParentPath(String path) {
        if (StrUtil.isBlank(path) || ROOT_PATH.equals(path)) {
            return ROOT_PATH;
        }
        
        int lastSeparatorIndex = path.lastIndexOf(SEPARATOR);
        if (lastSeparatorIndex <= 0) {
            return ROOT_PATH;
        }
        
        return path.substring(0, lastSeparatorIndex);
    }

    /**
     * 获取文件名
     *
     * @param path 文件路径
     * @return 文件名
     */
    public static String getFileName(String path) {
        if (StrUtil.isBlank(path)) {
            return "";
        }
        
        int lastSeparatorIndex = path.lastIndexOf(SEPARATOR);
        if (lastSeparatorIndex == -1) {
            return path;
        }
        
        return path.substring(lastSeparatorIndex + 1);
    }

    /**
     * 检查路径是否为根路径
     *
     * @param path 路径
     * @return 是否为根路径
     */
    public static boolean isRootPath(String path) {
        return ROOT_PATH.equals(normalizePath(path));
    }

    /**
     * 检查路径是否为子路径
     *
     * @param parentPath 父路径
     * @param childPath 子路径
     * @return 是否为子路径
     */
    public static boolean isSubPath(String parentPath, String childPath) {
        if (StrUtil.isBlank(parentPath) || StrUtil.isBlank(childPath)) {
            return false;
        }
        
        String normalizedParent = normalizePath(parentPath);
        String normalizedChild = normalizePath(childPath);
        
        return normalizedChild.startsWith(normalizedParent + SEPARATOR) || 
               normalizedChild.equals(normalizedParent);
    }

    /**
     * 获取相对路径
     *
     * @param basePath 基础路径
     * @param fullPath 完整路径
     * @return 相对路径
     */
    public static String getRelativePath(String basePath, String fullPath) {
        if (StrUtil.isBlank(basePath) || StrUtil.isBlank(fullPath)) {
            return "";
        }
        
        String normalizedBase = normalizePath(basePath);
        String normalizedFull = normalizePath(fullPath);
        
        if (normalizedFull.startsWith(normalizedBase)) {
            String relative = normalizedFull.substring(normalizedBase.length());
            if (relative.startsWith(SEPARATOR)) {
                relative = relative.substring(1);
            }
            return relative;
        }
        
        return normalizedFull;
    }

    /**
     * 构建用户根路径
     *
     * @param userId 用户ID
     * @return 用户根路径
     */
    public static String buildUserRootPath(Long userId) {
        return buildPath("user", userId.toString());
    }

    /**
     * 构建项目根路径
     *
     * @param projectId 项目ID
     * @return 项目根路径
     */
    public static String buildProjectRootPath(Long projectId) {
        return buildPath("project", projectId.toString());
    }

    /**
     * 构建文件存储路径
     *
     * @param userId 用户ID
     * @param fileName 文件名
     * @return 文件存储路径
     */
    public static String buildFileStoragePath(Long userId, String fileName) {
        String extension = CdFileUtils.getFileExtension(fileName);
        String fileType = CdFileUtils.getFileType(fileName).getCode();
        
        return buildPath("files", fileType, userId.toString(), 
                       System.currentTimeMillis() + "." + extension);
    }

    /**
     * 构建文件夹存储路径
     *
     * @param userId 用户ID
     * @param folderName 文件夹名
     * @return 文件夹存储路径
     */
    public static String buildFolderStoragePath(Long userId, String folderName) {
        return buildPath("folders", userId.toString(), 
                       System.currentTimeMillis() + "_" + folderName);
    }

    /**
     * 验证路径安全性
     *
     * @param path 路径
     * @return 是否安全
     */
    public static boolean isSafePath(String path) {
        if (StrUtil.isBlank(path)) {
            return false;
        }
        
        // 检查是否包含危险字符
        String[] dangerousChars = {"..", "~", "$", "&", "|", ";", "`", "(", ")", "<", ">", "\"", "'"};
        for (String dangerousChar : dangerousChars) {
            if (path.contains(dangerousChar)) {
                return false;
            }
        }
        
        return true;
    }

    /**
     * 清理路径
     *
     * @param path 原始路径
     * @return 清理后的路径
     */
    public static String cleanPath(String path) {
        if (StrUtil.isBlank(path)) {
            return ROOT_PATH;
        }
        
        // 移除危险字符
        path = path.replaceAll("[^a-zA-Z0-9/._-]", "");
        
        // 规范化路径
        return normalizePath(path);
    }
}
